"use client"

import type React from "react"
import { createContext, useContext, useState, useCallback, useRef } from "react"
import { Animated, StyleSheet, View, Text, Platform } from "react-native"
import { CheckCircle, AlertCircle, Info, AlertTriangle } from "lucide-react-native"
import { theme } from "../../../constants/theme"

// 消息类型
export type MessageType = "success" | "error" | "info" | "warning"

// 消息项接口
export interface MessageItem {
    id: string
    type: MessageType
    content: string
    duration: number
}

// 上下文接口
interface MessageContextType {
    addMessage: (type: MessageType, content: string, duration?: number) => void
    removeMessage: (id: string) => void
    messages: MessageItem[]
}

// 创建上下文
const MessageContext = createContext<MessageContextType | undefined>(undefined)

// 消息提供者组件
export const MessageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [messages, setMessages] = useState<MessageItem[]>([])
    const animationValues = useRef<{ [key: string]: Animated.Value }>({})
    const scaleValues = useRef<{ [key: string]: Animated.Value }>({})

    // 添加消息
    const addMessage = useCallback((type: MessageType, content: string, duration = 3000) => {
        const id = Date.now().toString()

        // 创建动画值
        animationValues.current[id] = new Animated.Value(0)
        scaleValues.current[id] = new Animated.Value(0.9)

        // 添加消息
        setMessages((prev) => [...prev, { id, type, content, duration }])

        // 淡入动画
        Animated.parallel([
            Animated.timing(animationValues.current[id], {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }),
            Animated.spring(scaleValues.current[id], {
                toValue: 1,
                friction: 8,
                tension: 40,
                useNativeDriver: true,
            }),
        ]).start()

        // 设置自动移除
        setTimeout(() => {
            // 淡出动画
            Animated.parallel([
                Animated.timing(animationValues.current[id], {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.timing(scaleValues.current[id], {
                    toValue: 0.9,
                    duration: 300,
                    useNativeDriver: true,
                }),
            ]).start(() => {
                removeMessage(id)
                delete animationValues.current[id]
                delete scaleValues.current[id]
            })
        }, duration)
    }, [])

    // 移除消息
    const removeMessage = useCallback((id: string) => {
        setMessages((prev) => prev.filter((message) => message.id !== id))
    }, [])

    return (
        <MessageContext.Provider value={{ addMessage, removeMessage, messages }}>
            {children}
            <View style={styles.messageContainer} pointerEvents="none">
                {messages.map((message) => (
                    <Animated.View
                        key={message.id}
                        style={[
                            styles.messageWrapper,
                            {
                                opacity: animationValues.current[message.id],
                                transform: [
                                    { scale: scaleValues.current[message.id] },
                                    {
                                        translateY: animationValues.current[message.id].interpolate({
                                            inputRange: [0, 1],
                                            outputRange: [-20, 0],
                                        }),
                                    },
                                ],
                            },
                        ]}
                    >
                        <View style={styles.messageItem}>
                            <View style={[styles.iconCircle, getIconStyle(message.type)]}>
                                <MessageIcon type={message.type} />
                            </View>
                            <Text style={styles.messageText}>{message.content}</Text>
                        </View>
                    </Animated.View>
                ))}
            </View>
        </MessageContext.Provider>
    )
}

// 消息图标组件
const MessageIcon: React.FC<{ type: MessageType }> = ({ type }) => {
    switch (type) {
        case "success":
            return <CheckCircle size={14} color="#FFFFFF" />
        case "error":
            return <AlertCircle size={14} color="#FFFFFF" />
        case "warning":
            return <AlertTriangle size={14} color="#FFFFFF" />
        case "info":
        default:
            return <Info size={14} color="#FFFFFF" />
    }
}

// 获取图标样式
const getIconStyle = (type: MessageType) => {
    switch (type) {
        case "success":
            return { backgroundColor: theme.colors.secondary.green.default }
        case "error":
            return { backgroundColor: theme.colors.secondary.red.default }
        case "warning":
            return { backgroundColor: theme.colors.secondary.orange.default }
        case "info":
        default:
            return { backgroundColor: theme.colors.primary.default }
    }
}

// 使用上下文的钩子
export const useMessage = () => {
    const context = useContext(MessageContext)
    if (!context) {
        throw new Error("useMessage must be used within a MessageProvider")
    }
    return context
}

// 样式
const styles = StyleSheet.create({
    messageContainer: {
        position: "absolute",
        top: 100,
        left: 0,
        right: 0,
        alignItems: "center",
        zIndex: 9999,
    },
    messageWrapper: {
        marginBottom: theme.spacing.md,
        width: "auto",
        maxWidth: "80%",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.15)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.6,
                shadowRadius: 8,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    messageItem: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: "rgba(255, 255, 255, 0.85)",
        borderRadius: 20,
        paddingVertical: 8,
        paddingHorizontal: 12,
        paddingRight: 16,
    },
    iconCircle: {
        width: 24,
        height: 24,
        borderRadius: 12,
        alignItems: "center",
        justifyContent: "center",
        marginRight: 8,
    },
    messageText: {
        fontSize: 14,
        fontWeight: "500",
        color: theme.colors.neutral.black,
    },
})

